package com.sunday.haowushop.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.haowushop.R;
import com.sunday.haowushop.adapter.CommonAdapter;
import com.sunday.haowushop.adapter.ViewHolder;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.ShareRecord;
import com.sunday.haowushop.http.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/7/10.
 *
 * 分享记录
 */

public class ShareRecordActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private List<ShareRecord> dataSet=new ArrayList<>();
    private CommonAdapter<ShareRecord> adapter;
    private long memberId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);
        ButterKnife.bind(this);
        titleView.setText("分享记录");
        memberId = BaseApp.getInstance().getMember().getId();
        initRecyclerView();
        getData();
    }

    private LinearLayoutManager layoutManager;
    private void initRecyclerView(){
        emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter= new CommonAdapter<ShareRecord>(mContext,R.layout.share_list_item,dataSet) {
            @Override
            public void convert(ViewHolder holder, ShareRecord shareRecord) {
                bind(holder,shareRecord);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo=1;
                getData();
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }


    private void bind(ViewHolder holder, final ShareRecord shareRecord){
        ((TextView)holder.getView(R.id.text_money)).setText(String.format("¥%s云币",shareRecord.getTotalMoney().setScale(0, RoundingMode.HALF_UP)));
        ((TextView)holder.getView(R.id.text_time)).setText(shareRecord.getCreateTime());
        final String shareStatus=shareRecord.getStatus()==2?"已过期":shareRecord.getNow()==0?"已领完":"领取中";
        ((TextView)holder.getView(R.id.text_num)).setText(String.format("%1$s%2$d/%3$d",shareStatus,shareRecord.getTotal()-shareRecord.getNow(),shareRecord.getTotal()));

        View.OnClickListener onClickListener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent=new Intent(mContext,YunbiShareDetailActivity.class);
                intent.putExtra("shareRecord",shareRecord);
                startActivity(intent);
            }
        };
        holder.setOnClickListener(R.id.relative_layout,onClickListener);

    }

    private int pageNo = 1;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private void getData(){
        Call<ResultDO<List<ShareRecord>>> call = ApiClient.getApiAdapter().getShareRecordList(memberId, pageNo,  Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<ShareRecord>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<ShareRecord>>> call, Response<ResultDO<List<ShareRecord>>> response) {
                if (isFinish) {
                    return;
                }
                ptrFrame.refreshComplete();
                ResultDO<List<ShareRecord>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() ==  Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<ShareRecord>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }



}
